package cn.tangshh.universal.core.api;

import cn.hutool.core.collection.ListUtil;
import cn.tangshh.universal.core.util.MessageUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.http.HttpStatus;

import java.util.Collection;

/**
 * 分页返回数据
 *
 * @author Tang
 * @version v1.0
 */
@Data
@Schema(title = "分页返回数据")
@EqualsAndHashCode(callSuper = true)
public class PR<T> extends R<Collection<T>> {
    @Schema(title = "页码")
    private long pageNum;

    @Schema(title = "页大小")
    private long pageSize;

    @Schema(title = "总数量")
    private long totalElements;

    @Schema(title = "总数量")
    private long totalPage;

    public static <T> PR<T> ok() {
        RCode success = RCode.SUCCESS;
        PR<T> pr = new PR<>();
        pr.setData(ListUtil.empty());
        pr.setMsg(MessageUtil.convert(success.getMessage()));
        pr.setCode(success);
        pr.setSuccess(true);
        return pr;
    }

    public static <T> PR<T> ok(long totalElements, Collection<T> data) {
        PR<T> pr = ok();
        pr.setData(data);
        pr.setTotalElements(totalElements);
        return pr;
    }

    public static <T> PR<T> fail() {
        RCode fail = RCode.BAD_REQUEST;
        PR<T> pr = new PR<>();
        pr.setMsg(MessageUtil.convert(fail.getMessage()));
        pr.setCode(fail);
        pr.setSuccess(false);
        return pr;
    }


    public static <T> PR<T> fail(String msg) {
        RCode fail = RCode.BAD_REQUEST;
        PR<T> pr = new PR<>();
        pr.setMsg(MessageUtil.convert(msg));
        pr.setCode(fail);
        pr.setSuccess(false);
        return pr;
    }

    public static <T> PR<T> of(RCode rCode) {
        PR<T> pr = new PR<>();
        pr.setMsg(MessageUtil.convert(rCode.getMessage()));
        pr.setCode(rCode);
        pr.setSuccess(rCode.getCode() <= 300);
        return pr;
    }

    public static <T> PR<T> of(HttpStatus status) {
        PR<T> pr = new PR<>();
        pr.setMsg(status.getReasonPhrase());
        pr.setCode(RCode.of(status.value()));
        pr.setSuccess(status.is2xxSuccessful());
        return pr;
    }

}